package com.gao.baseboot;

import com.gao.baseboot.prototype.PrototypeBean;
import com.gao.baseboot.request.RequestBean;
import com.gao.baseboot.session.SessionBean;
import com.gao.baseboot.singleton.SingletonBean;
import com.gao.baseboot.singletondiprototype.CommonDi;
import com.gao.baseboot.singletondiprototype.mi.MethodInjection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author GaoXi
 * @date 2022/2/21 14:21
 */
@Slf4j
@RestController
public class TestController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    @RequestMapping("testSingleton")
    public String testSingleton() {
        return applicationContext.getBean(SingletonBean.class).toString();
    }


    @RequestMapping("testPrototype")
    public String testPrototype() {
        return applicationContext.getBean(PrototypeBean.class).toString();
    }


    @RequestMapping("testRequest")
    public String testRequest() {
        String s = applicationContext.getBean(RequestBean.class).toString();
        String s1 = applicationContext.getBean(RequestBean.class).toString();
        Assert.isTrue(s.equals(s1), "居然不相等");
        log.info("是否一致{}", s.equals(s1));
        return s;
    }

    @RequestMapping("testSession")
    public String testSession(HttpServletRequest request, HttpSession httpSession) {
        log.info("sessionId:{}", httpSession.getId());
        httpSession.setMaxInactiveInterval(20);
        return applicationContext.getBean(SessionBean.class).toString();
    }

    /**
     * 常规的注入手段，protoType 的bean只会被注入一次
     *
     * @return
     */
    @Autowired
    private CommonDi commonDi;

    @RequestMapping("testCommonSingletonDiPrototype")
    public String testCommonSingletonDiPrototype() {
        return commonDi.getPrototypeBean().toString();
    }


    /**
     * 测试方法注入
     */
    @Autowired
    private MethodInjection methodInjection;

    @RequestMapping("testMiSingletonDiPrototype")
    public String testMiSingletonDiPrototype() {
        return methodInjection.getPrototypeBean().toString();
    }


}
